#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
//创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n != -1);
    (void)n;
#ifdef DEBUG
    cout<<"pipefd[0] = "<<pipefd[0]<<endl;
    cout<<"pipefd[1] = "<<pipefd[1]<<endl;
#endif
//创建子进程
    int ret = fork();
    if(ret == 0)//子进程
    {
        //首先要关闭没用的文件描述符，我希望子进程只从管道里读数据,所以要关闭写的描述符
        close(pipefd[1]);
        //创建缓冲区
        char buffer[1024] = {0};
        while(1)
        {
            ssize_t r = read(pipefd[0],buffer,sizeof (buffer) - 1);
            assert(r != -1);
            (void)r;
            if(r>0)
            {
                cout<<"child [ "<<getpid()<<" ] :get a massage from father [ "<<getppid()<<" ] : "<<buffer<<endl;
            }
            else if(r == 0)
            {
                cout<<"child:我读到文件结尾了，我也要结束了\n"<<endl;
                break;
            }
        }
        exit(0);
    }
    //父进程
    close(pipefd[0]);
    char buffer[1024] = {0};
    int count = 0;
    while(1)
    {
        snprintf(buffer,sizeof buffer,"%s : %d",buffer,count++);
        write(pipefd[1],buffer,strlen(buffer));
        sleep(1);
        if(count == 10)
        {
            cout<<"father:我的消息发送完了\n"<<endl;
            break;
        }
    }
    close(pipefd[1]);
    pid_t pidret = waitpid(-1,nullptr,0);
    assert(pidret>0);
    (void)pidret;
    
    return 0;
}
